package com.tx.server;

import com.tx.listener.wslistener.MarketdataWsListener;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * @author dengguoxing
 * @date 2019/10/31
 * description websocket服务器启动
 **/
@Component
public class WebSocketServer {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${netty.server.port}")
    private Integer PORT;

    @Value("${netty.server.path}")
    private String PATH;

   @Autowired
   private MarketdataWsListener marketdataWsListener;

    private EventLoopGroup boss = new NioEventLoopGroup(1);
    private EventLoopGroup work = new NioEventLoopGroup();

    public void start() throws InterruptedException {

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(boss, work)
                    .channel(NioServerSocketChannel.class)
                    //保持长连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new WebSocketServerInitializer(marketdataWsListener, PATH));

            ChannelFuture channelFuture = b.bind(PORT).sync();

            if (channelFuture.isSuccess()) {
                logger.info("启动 Netty 服务器成功，监听链接端口：http://127.0.0.1:" + PORT);
            }

            // 等待关闭
            Channel ch = channelFuture.channel();
            ch.closeFuture().sync();
        } catch (Exception e) {
            logger.error("启动 Netty 服务器失败，失败原因：", e);
        } finally {
            boss.shutdownGracefully().syncUninterruptibly();
            work.shutdownGracefully().syncUninterruptibly();
            logger.info("关闭 Netty 成功");
        }
    }

}
